package top.lingkang.finalsession.solon;

import org.noear.solon.core.handle.SessionState;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashMap;

/**
 * @author lingkang
 * @create by 2024/5/9 17:39
 */
public class FinalSessionState extends HashMap<String, Object> implements SessionState, Serializable {
    private final String id;
    private final long creationTime;
    private long lastAccessedTime;
    public static ThreadLocal<Boolean> existsUpdate = ThreadLocal.withInitial(() -> false);

    public FinalSessionState(String id) {
        this.id = id;
        creationTime = System.currentTimeMillis();
        lastAccessedTime = creationTime;
    }

    @Override
    public boolean replaceable() {
        return false;
    }

    @Override
    public String sessionId() {
        return id;
    }

    @Override
    public String sessionChangeId() {
        throw new UnsupportedOperationException("final-session-solon 不支持此方法");
    }

    @Override
    public Collection<String> sessionKeys() {
        return keySet();
    }

    @Override
    public <T> T sessionGet(String key, Class<T> clz) {
        Object val = get(key);
        if (val == null)
            return null;
        return (T) val;
    }

    @Override
    public void sessionSet(String key, Object val) {
        put(key, val);
        existsUpdate.set(true);
    }

    @Override
    public void sessionRemove(String key) {
        remove(key);
        existsUpdate.set(true);
    }

    @Override
    public void sessionClear() {
        clear();
        existsUpdate.set(true);
    }

    @Override
    public Object remove(Object key) {
        existsUpdate.set(true);
        return super.remove(key);
    }

    @Override
    public void sessionReset() {
        throw new UnsupportedOperationException("final-session-solon 不支持此方法");
    }

    public void updateAccessTime(long lastAccessedTime) {
        this.lastAccessedTime = lastAccessedTime;
        existsUpdate.set(true);
    }

    public long getCreationTime() {
        return creationTime;
    }

    public long getLastAccessedTime() {
        return lastAccessedTime;
    }

}
